<template>
  <div class='login'>
    <van-nav-bar title="登录"/>

<van-cell-group>
  <van-field
    v-model="phone"
    required
    label="手机号"
    placeholder="请输入手机号"
    :error-message="mobile_errmsg"
    @input="validate"
  />
   <van-field
    v-model="sms"
    center
    clearable
    label="短信验证码"
    placeholder="请输入短信验证码"
    :error-message="code_errmsg"
    @input="validate"
  >
  <template #button>
    <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
  </template>
</van-field>
</van-cell-group>
<div class="btn-wrap">
  <van-button type="info" @click="login">登录按钮</van-button>
</div>
  </div>
</template>

<script>
import { reqLogin, reqSendCode } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      phone: '13912345567',
      sms: '246810',
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },
  methods: {
    validate () {
      if (this.phone.trim() === '') {
        this.mobile_errmsg = '手机号不能为空'
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.mobile_errmsg = '手机号格式不合法'
        return
      }
      this.mobile_errmsg = ''
      if (this.sms.trim() === '') {
        this.code_errmsg = '验证码不能为空'
        return
      }
      if (!/^\d{6}$/.test(this.sms)) {
        this.code_errmsg = '验证码格式不合法'
        return
      }
      this.code_errmsg = ''
      return true
    },
    async sendCode () {
      if (!this.validate()) return
      try {
        await reqSendCode(this.phone)
        this.$toast.success('验证码发送成功 - 246810')
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    },
    async login () {
      if (!this.validate()) return
      this.$toast.loading({
        message: '登录中',
        forbidClick: true,
        overlay: true,
        duration: 0
      })
      try {
        const res =
        await reqLogin(this.phone, this.sms)
        this.$store.commit('user/setTokenInfo', res.data.token)
        this.$store.commit('user/setRefreshToken', res.data.refresh_token)
        this.$toast.success('登录成功')
        this.$router.push(this.$route.query.backto || '/')
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.btn-wrap{
  padding: 20px;
  .van-button{
     width: 100%;
     color:#fff;
     border-radius: 5px;
  }
}
</style>
